package ymap

import "sync"

func NewRegister[V any]() *Register[string, V] {
	return New[string, V]()
}

func New[K ~string, V any]() *Register[K, V] {
	return &Register[K, V]{
		container: sync.Map{},
	}
}

type Register[K ~string, V any] struct {
	container sync.Map
}

func (r *Register[K, V]) Register(key K, value V) {
	r.container.Store(key, value)
}

func (r *Register[K, V]) Unregister(key K) {
	r.container.Delete(key)
}

func (r *Register[K, V]) Get(key K) (V, bool) {
	value, ok := r.container.Load(key)
	if !ok {
		return *new(V), false
	}
	return value.(V), true
}

// get all
func (r *Register[K, V]) GetAllMap() map[K]V {
	m := make(map[K]V)
	r.container.Range(func(key, value interface{}) bool {
		m[key.(K)] = value.(V)
		return true
	})
	return m
}

// get all
func (r *Register[K, V]) GetAllSlice() []V {
	var result []V
	r.container.Range(func(key, value interface{}) bool {
		result = append(result, value.(V))
		return true
	})
	return result
}
